package com.web.exiaodao.business.service.impl;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.InsHotelRoomsTable;
import com.web.exiaodao.business.entity.Order;
import com.web.exiaodao.business.repository.InsHotelRoomsTableRepository;
import com.web.exiaodao.business.repository.OrderRepository;
import com.web.exiaodao.business.service.InsHotelRoomsTableService;
import com.web.exiaodao.business.service.InsRoomsOrderService;
import com.web.exiaodao.remote.vo.InsHotelRoomsTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("InsHotelRoomsTableService")
@Transactional(readOnly = false)
public class InsHotelRoomsTableServiceImpl extends BaseService<InsHotelRoomsTable> implements InsHotelRoomsTableService {

    private static final Logger LOGGER = Logger.getLogger(InsHotelRoomsTableServiceImpl.class);

    @Autowired
    InsHotelRoomsTableRepository insHotelRoomsTableRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private InsRoomsOrderService insRoomsOrderService;

    /**
     * 查询单条InsHotelRoomsTable信息
     * //@param tId
     *
     * @return 返回单个InsHotelRoomsTable对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<InsHotelRoomsTable> findOne(Long modelId) throws BusinessException {
        InsHotelRoomsTable obj = new InsHotelRoomsTable();
        if (modelId != 0) {
            obj = insHotelRoomsTableRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<InsHotelRoomsTable> xr = new XaResult<InsHotelRoomsTable>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(obj);
            LOGGER.info("后台----->查询单个实体----->InsHotelRoomsTable");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    //根据机构编码查询酒店房间
	@Override
	public XaResult<Page<InsHotelRoomsTableVo>> findInsHotelRoomsListById(Integer status,
			Map<String,Object> filterParams,Pageable pageable,Long modelId) throws BusinessException {
//		SELECT id,hotel_rooms_brief,hotel_rooms_inventory,hotel_rooms_price,hotel_rooms_price_unit,hotel_rooms_publish_date_time,hourse_type,create_time,STATUS
//		FROM `tb_xa_inshotelroomstable` WHERE STATUS<>3 AND institution_id = 1
		StringBuffer sql = new StringBuffer("SELECT id,hotel_rooms_name,hotel_rooms_brief,hotel_rooms_inventory,hotel_rooms_price,hotel_rooms_price_unit,hourse_type,create_time,STATUS ");
		sql.append("FROM `tb_xa_inshotelroomstable` ");
		sql.append("WHERE STATUS<>").append(XaConstant.Status.delete);
		sql.append(" AND institution_id = ").append(modelId);
		StringBuffer sql1 = new StringBuffer("select count(*) ");
		sql1.append("FROM `tb_xa_inshotelroomstable` ");
		sql1.append("WHERE STATUS<>").append(XaConstant.Status.delete);
		sql1.append(" AND institution_id = ").append(modelId);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_hotelRooms_Name"))){
			sql.append(" AND hotel_rooms_name ").append(" like '%").append(filterParams.get("LIKE_hotelRooms_Name")).append("%' ");
			sql1.append(" AND hotel_rooms_name ").append(" like '%").append(filterParams.get("LIKE_hotelRooms_Name")).append("%' ");
		}
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_AutherID"))){
			sql.append(" AND hourse_type = ").append(filterParams.get("EQ_hourseType")).append(" ");
			sql1.append(" AND hourse_type = ").append(filterParams.get("EQ_hourseType")).append(" ");
		}
		sql.append(" ORDER BY create_time desc");
		sql1.append(" ORDER BY create_time desc");
		List<Object[]> objs = this.query(sql.toString(), pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
		List<InsHotelRoomsTableVo> vos = new ArrayList<InsHotelRoomsTableVo>();
		for (Object[] obj : objs) {
			InsHotelRoomsTableVo vo = new InsHotelRoomsTableVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setHotelRooms_Name(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setHotelRooms_Brief(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setHotelRooms_Inventory(XaUtil.isEmpty(obj[3])?0:Integer.valueOf(obj[3].toString()));
			vo.setHotelRooms_Price(XaUtil.isEmpty(obj[4])?0:Double.valueOf(obj[4].toString()));
			vo.setHotelRooms_Price_unit(XaUtil.isEmpty(obj[5])?"":obj[5].toString());
			vo.setHourseType(XaUtil.isEmpty(obj[6])?"":obj[6].toString());
			vo.setCreateTime(XaUtil.isEmpty(obj[7])?"":obj[7].toString());
			vos.add(vo);
		}
		List<Object[]> obj1=this.query(sql1.toString(), null, null);
		int count=Integer.parseInt(obj1.get(0)+"");	
		Page<InsHotelRoomsTableVo> page= new MyPage<InsHotelRoomsTableVo>(pageable.getPageNumber(),pageable.getPageSize(),vos,count);
		XaResult<Page<InsHotelRoomsTableVo>> xr=new XaResult<Page<InsHotelRoomsTableVo>>();
		xr.setObject(page);
		return xr;
	}
    
    /**
     * 分页查询状态非status的InsHotelRoomsTable数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象InsHotelRoomsTable集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<InsHotelRoomsTable>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<InsHotelRoomsTable> page = insHotelRoomsTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), InsHotelRoomsTable.class), pageable);
        XaResult<Page<InsHotelRoomsTable>> xr = new XaResult<Page<InsHotelRoomsTable>>();
        xr.setObject(page);
        LOGGER.info("后台----->分页查询实体集合（状态不等于）----->InsHotelRoomsTable");
        return xr;
    }

    /**
     * 分页查询状态status的InsHotelRoomsTable数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象InsHotelRoomsTable集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<InsHotelRoomsTable>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<InsHotelRoomsTable> page = insHotelRoomsTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), InsHotelRoomsTable.class), pageable);
        XaResult<Page<InsHotelRoomsTable>> xr = new XaResult<Page<InsHotelRoomsTable>>();
        xr.setObject(page);
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->InsHotelRoomsTable");
        return xr;
    }

    /**
     * 保存InsHotelRoomsTable信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<InsHotelRoomsTable> saveOrUpdate(InsHotelRoomsTable model) throws BusinessException {
        InsHotelRoomsTable obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = insHotelRoomsTableRepository.findOne(model.getId());
        } else {
            obj = new InsHotelRoomsTable();
        }
        obj.setHotelRooms_Name(XaUtil.isNotEmpty(model.getHotelRooms_Name()) ? model.getHotelRooms_Name() : obj.getHotelRooms_Name());
        obj.setHotelRooms_Price(XaUtil.isNotEmpty(model.getHotelRooms_Price()) ? model.getHotelRooms_Price() : obj.getHotelRooms_Price());
        obj.setHotelRooms_Inventory(XaUtil.isNotEmpty(model.getHotelRooms_Inventory()) ? model.getHotelRooms_Inventory() : obj.getHotelRooms_Inventory());
        obj.setInstitutionId(XaUtil.isNotEmpty(model.getInstitutionId()) ? model.getInstitutionId() : obj.getInstitutionId());
        obj.setHotelRooms_Brief(XaUtil.isNotEmpty(model.getHotelRooms_Brief()) ? model.getHotelRooms_Brief() : obj.getHotelRooms_Brief());
        obj.setHotelRooms_Price_unit(XaUtil.isNotEmpty(model.getHotelRooms_Price_unit()) ? model.getHotelRooms_Price_unit() : obj.getHotelRooms_Price_unit());
        obj.setHourseType(XaUtil.isNotEmpty(model.getHourseType()) ? model.getHourseType() : obj.getHourseType());
        obj.setBanner(XaUtil.isNotEmpty(model.getBanner()) ? model.getBanner() : obj.getBanner());
        obj.setIsSellByCard(XaUtil.isNotEmpty(model.getIsSellByCard()) ? model.getIsSellByCard() : obj.getIsSellByCard());
        obj.setBookPrice(XaUtil.isNotEmpty(model.getBookPrice()) ? model.getBookPrice() : obj.getBookPrice());
        obj = insHotelRoomsTableRepository.save(obj);
        XaResult<InsHotelRoomsTable> xr = new XaResult<InsHotelRoomsTable>();
        xr.setObject(obj);
        LOGGER.info("后台新增或编辑数据成功！");

        //生成未来1个月的订单信息或者24个月的
        //insRoomsOrderService.findOne(null);
        return xr;
    }

    /**
     * 修改InsHotelRoomsTable状态，可一次修改多条   3删除  -1锁定  1正常
     * //@param userId
     *
     * @param modelIds
     * @param status
     * @return 返回InsHotelRoomsTable对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<InsHotelRoomsTable> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<InsHotelRoomsTable> xr = new XaResult<InsHotelRoomsTable>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                InsHotelRoomsTable obj = insHotelRoomsTableRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    if (status == XaConstant.Status.delete) {
                        //这里是物理删除，否则机构查询的时候，有问题
                        insHotelRoomsTableRepository.delete(obj);
                    } else {
                        obj.setStatus(status);
                        obj = insHotelRoomsTableRepository.save(obj);
                    }
                }
            }
        }
        LOGGER.info("批量修改数据状态成功！");
        return xr;
    }

    //更新库存
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateHotelRoomsStockNum() throws BusinessException {
        //库存换回去的情况
        //1:订单取消
        //2:手动退房
        //3:退房时间到自动退房

        //查询所有的(hotelRooms)PAYED 状态的订单,如果退房时间到,就自动进行退房处理
        Map<String, SearchFilter> filters = new HashMap<>();
        filters.put("status", new SearchFilter("status", Operator.NE, XaConstant.Status.delete));
        filters.put("orderState", new SearchFilter("orderState", Operator.EQ, JConstant.OrderStatus.PAYED));
        filters.put("orderType", new SearchFilter("orderType", Operator.EQ, JConstant.Order_CommentType.GOODS));
        List<Order> orders = orderRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), Order.class));

        for (int i = 0; orders != null && i < orders.size(); ++i) {
            Order order = orders.get(i);
            //时间如果离店日期到了
            String checkInDate = order.getHourse_checkinTime();
            int duration = order.getHourse_checkin_duration();
            String unit = order.getHourse_checkin_duration_unit();
            Date leaveDate = null;
            Date todayDate = DateUtils.getTodayNoMin();
            if ("天".equals(unit)) {
                Date date = DateUtils.formatStr(checkInDate, DateUtils.YYYYMMDD);
                leaveDate = org.apache.commons.lang3.time.DateUtils.addDays(date, duration);
            } else if ("月".equals(unit)) {
                Date date = DateUtils.formatStr(checkInDate, DateUtils.YYYYMMDD);
                leaveDate = org.apache.commons.lang3.time.DateUtils.addMonths(date, duration);
            }
            if (leaveDate != null && todayDate != null && leaveDate.compareTo(todayDate)!=1) {
                //进行离店处理1:订单 状态 2:房子 库存
                order.setOrderState(JConstant.OrderStatus.UN_COMMENT+"");
                orderRepository.save(order);

                InsHotelRoomsTable roomsTable = insHotelRoomsTableRepository.findOne(order.getService_object_id());
                int inventory = roomsTable.getHotelRooms_Inventory();
                int hourseNum = order.getService_num().intValue();
                int count = inventory + hourseNum;
                roomsTable.setHotelRooms_Inventory(count);
                insHotelRoomsTableRepository.save(roomsTable);

                LOGGER.info("房子库存恢复inventory=" + inventory + ";count=" + count);
            }
        }
    }

}
